"""
日志配置模块
"""
import logging
import sys
from datetime import datetime
from pathlib import Path


class ColoredFormatter(logging.Formatter):
    """彩色日志格式器"""
    
    # ANSI颜色代码
    COLORS = {
        'DEBUG': '\033[36m',    # 青色
        'INFO': '\033[32m',     # 绿色
        'WARNING': '\033[33m',  # 黄色
        'ERROR': '\033[31m',    # 红色
        'CRITICAL': '\033[35m', # 紫色
    }
    RESET = '\033[0m'  # 重置颜色
    
    def format(self, record):
        # 获取颜色
        color = self.COLORS.get(record.levelname, '')
        
        # 格式化时间
        record.asctime = datetime.fromtimestamp(record.created).strftime('%Y-%m-%d %H:%M:%S')
        
        # 应用颜色
        if color:
            record.levelname = f"{color}{record.levelname}{self.RESET}"
            record.msg = f"{color}{record.msg}{self.RESET}"
        
        return super().format(record)


def setup_logger(name: str = "wechat_article_generator", level: int = logging.INFO) -> logging.Logger:
    """设置日志器"""
    
    # 创建日志器
    logger = logging.getLogger(name)
    logger.setLevel(level)
    
    # 避免重复添加处理器
    if logger.handlers:
        return logger
    
    # 创建日志目录
    log_dir = Path("logs")
    log_dir.mkdir(exist_ok=True)
    
    # 日志格式
    formatter = logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(filename)s:%(lineno)d - %(message)s'
    )
    
    # 彩色控制台格式器
    colored_formatter = ColoredFormatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(filename)s:%(lineno)d - %(message)s'
    )
    
    # 控制台处理器
    console_handler = logging.StreamHandler(sys.stdout)
    console_handler.setLevel(logging.INFO)
    console_handler.setFormatter(colored_formatter)
    logger.addHandler(console_handler)
    
    # 文件处理器 - 所有日志
    file_handler = logging.FileHandler(
        log_dir / f"{name}_{datetime.now().strftime('%Y%m%d')}.log",
        encoding='utf-8'
    )
    file_handler.setLevel(logging.DEBUG)
    file_handler.setFormatter(formatter)
    logger.addHandler(file_handler)
    
    # 错误日志文件处理器
    error_handler = logging.FileHandler(
        log_dir / f"{name}_error_{datetime.now().strftime('%Y%m%d')}.log",
        encoding='utf-8'
    )
    error_handler.setLevel(logging.ERROR)
    error_handler.setFormatter(formatter)
    logger.addHandler(error_handler)
    
    return logger


# 创建全局日志器
logger = setup_logger()


def log_function_call(func_name: str, args: dict = None, result: any = None):
    """记录函数调用日志"""
    if args:
        logger.debug(f"调用函数 {func_name}，参数: {args}")
    else:
        logger.debug(f"调用函数 {func_name}")
    
    if result is not None:
        logger.debug(f"函数 {func_name} 返回: {str(result)[:100]}...")


def log_api_call(api_name: str, url: str, status_code: int = None, response_time: float = None):
    """记录API调用日志"""
    if status_code and response_time:
        logger.info(f"API调用 {api_name}: {url} - 状态码: {status_code}, 响应时间: {response_time:.2f}s")
    else:
        logger.info(f"API调用 {api_name}: {url}")


def log_error(error: Exception, context: str = ""):
    """记录错误日志"""
    if context:
        logger.error(f"错误发生在 {context}: {str(error)}", exc_info=True)
    else:
        logger.error(f"错误: {str(error)}", exc_info=True)